<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/19 0019
 * Time: 10:31
 */

namespace frontend\controllers;
// header("Access-Control-Allow-Origin:http://medicals.qingguo188.com");
// header("Access-Control-Allow-Origin:http://localhost:8080");
header("Access-Control-Allow-Methods:POST,GET");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Access-Control-Allow-Credentials: true");
use common\models\User;
use common\models\UserCode;
use common\models\UserSecondary;
use common\models\UserSignin;
use Yii;
// use yii\web\Controller;
use frontend\controllers\BaseController;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
 * User controller
 */
class UserController extends BaseController
{
    public function beforeAction($action)
    {
        if ($action->id == 'dologin' || $action->id == 'getphonenumber' || $action->id == 'register' || $action->id == 'sendsms'
            || $action->id == 'forgetpassword' || $action->id == 'forgetpassword' || $action->id == 'userslist' || $action->id == 'logout') {
            $this->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [

        ];
    }
    public function actionIslogin() {
        $session = Yii::$app->session;
        $session->open();
        //存在
        if (!!$session->has('session_id')) {
            $User = new User();
            $Secondary = new UserSecondary();
            $userInfo = $User::find()->where(["session_id" => $session['session_id'], 'status' => 1])->one();
            $usersecond = $Secondary::find()->where(["session_id" => $session['session_id'], 'status' => 1])->one();
            if (!!$userInfo) {
                $now_time =  time();
                $old_time = strtotime($userInfo->last_operation_time);
                $differ_time = $now_time - $old_time;
                if($differ_time > $session->timeout && $userInfo->is_login == 1){
                    //长时间未操作或非正常退出
                    $userInfo->is_login = 0;
                    $userInfo->session_id = null;
                    $userInfo->is_again = 0;
                    $session->destroy();
                    return $this->getjson(3,'登录已过期,请重新登录'.$session['session_id']);
                }
                return $this->getjson(1,'已登录'.$session['session_id']);
            }
            if (!!$usersecond) {
                $now_time =  time();
                $old_time = strtotime($usersecond->last_operation_time);
                $differ_time = $now_time - $old_time;
                if($differ_time > $session->timeout && $usersecond->is_login == 1){
                    //长时间未操作或非正常退出
                    $usersecond->is_login = 0;
                    $usersecond->session_id = null;
                    $usersecond->is_again = 0;
                    $session->destroy();
                    return $this->getjson(3,'登录已过期,请重新登录'.$session['session_id']);
                }
                return $this->getjson(1,'已登录'.$session['session_id']);
            }
            $session->remove('session_id');
            return $this->getjson(2,'账号在其他设备登录'.$session['session_id']);
        }
        return $this->getjson(4,'未登录'.$session['session_id']);
    }
    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionDologin()
    {
        $model = new User();
        $secondmodel = new UserSecondary;
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($data){
                //查询是否存在     并且需要判断状态
                $userInfo1 = $model::find()->where(["phone"=>$data['phone']])->one();
                $usersecond1 = $secondmodel::find()->where(["phone"=>$data['phone']])->one();
                $userInfo = $model::find()->where(["phone"=>$data['phone'],'status'=>1])->one();
                $usersecond = $secondmodel::find()->where(["phone"=>$data['phone'],'status'=>1])->one();

                if($userInfo1 && !$userInfo){
                    return $this->getjson(0,'此账号已经被冻结,请联系管理员');
                }

                if($usersecond1 && !$usersecond){
                    return $this->getjson(0,'此账号已经被冻结,请联系管理员');
                }

                if(!$userInfo && !$usersecond){
                    return $this->getjson(0,'此手机号不存在,请注册后登录');
                }
                //判断使用权是否过期
                if($userInfo){
                    $user_id = $userInfo['id'];
                }
                if($usersecond){
                    $user_id = $usersecond['user_id'];
                }


                $usersign = new UserSignin();
                $expried_time = $usersign::find()->where(['user_id'=>$user_id,'status'=>1])->one();
                if(!(strtotime($expried_time['expired_time'])-strtotime('now'))){
                    return $this->getjson(0,'您的使用权已经过期,请购买');
                }

                //判断密码是否正确,如果存在,则更新用户最后登录的ip和最后登录的时间
                if($userInfo || $usersecond){
                    $session = Yii::$app->session;
                    if($userInfo['password'] == $data['password'] && $userInfo['phone'] == $data['phone']){
                        // 判断是否登录 如果登录 提示已登录
                        // 如果未登录 更改登录状态 生成并存入session_id
                        // if($userInfo->is_login == 1){
                        //     return $this->getjson(0,'该用户已经登陆,请勿重复登陆'.$session['session_id']);
                        // }
                        $now_time =  time();
                        $old_time = strtotime($userInfo->last_operation_time);
                        $differ_time = $now_time - $old_time;
                        if($differ_time > $session->timeout && $userInfo->is_login == 1){
                            //非正常退出处理
                            $userInfo->is_login = 0;
                            $userInfo->session_id = null;
                            $userInfo->is_again = 0;
                            $session->destroy();
                        }
                        //不相等, 提示后 下次替换登录
                        if($userInfo->is_login == 1 && $userInfo->is_again == 0){
                            $userInfo->is_again = 1;
                            $userInfo->update(false);
                            return $this->getjson(0,'该用户已经登陆,请勿重复登陆'.$session['session_id']);
                        }
                        if ($userInfo->is_login == 1 && $userInfo->is_again == 1) {
                            $userInfo->is_login = 0;
                            $userInfo->session_id = null;
                            $userInfo->is_again = 0;
                            $userInfo->update(false);
                        }

                        $userlist = $userInfo;
                        $level = 1;
                        $userInfo->last_login_time = date('Y-m-d H:i:s',strtotime('now'));
                        $userInfo->last_login_ip = $_SERVER["REMOTE_ADDR"];
                        $userInfo->is_login = 1;
                        $userInfo->last_operation_time = date('Y-m-d H:i:s', strtotime('now'));
                        $userInfo->save();
                    }elseif($usersecond['password'] == $data['password'] && $usersecond['phone'] == $data['phone']){
                        // if($usersecond->is_login == 1){
                        //     return $this->getjson(0,'该用户已经登陆,请勿重复登陆');
                        // }
                        $now_time =  time();
                        $old_time = strtotime($usersecond->last_operation_time);
                        $differ_time = $now_time - $old_time;
                        if($differ_time > $session->timeout && $usersecond->is_login == 1){
                            //非正常退出处理
                            $usersecond->is_login = 0;
                            $usersecond->session_id = null;
                            $usersecond->is_again = 0;
                            $session->destroy();
                        }
                        //不相等, 提示后 下次替换登录
                        if($usersecond->is_login == 1 && $usersecond->is_again == 0){
                            $usersecond->is_again = 1;
                            $usersecond->update(false);
                            return $this->getjson(0,'该用户已经登陆,请勿重复登陆'.$session['session_id']);
                        }
                        if ($usersecond->is_login == 1 && $usersecond->is_again == 1) {
                            $usersecond->is_login = 0;
                            $usersecond->session_id = null;
                            $usersecond->is_again = 0;
                            $usersecond->update(false);
                        }

                        $userlist = $usersecond;
                        $level = 2;
                        $usersecond->last_login_time = date('Y-m-d H:i:s',strtotime('now'));
                        $usersecond->last_login_ip = $_SERVER["REMOTE_ADDR"];
                        $usersecond->is_login = 1;
                        $usersecond->last_operation_time = date('Y-m-d H:i:s', strtotime('now'));
                        $usersecond->save();
                    }else{
                        return $this->getjson(0,'手机号不存在,或者密码错误');
                    }

                    $userlist1['userid'] = $userlist['id'];
                    $userlist1['name'] = $userlist['name'];
                    $userlist1['password'] = $userlist['password'];
                    $userlist1['site'] = $userlist['site'];
                    $userlist1['level'] = $level;
                    //存入Session
                    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
                    $lc = strlen($chars) - 1;
                    for ($i = 0, $str = '';$i < 25; $i++){
                        $str .= $chars[mt_rand(0, $lc)];
                    }
                    $session['session_id'] = $str;
                    $session['user_id'] = $userlist1['userid'];
                    $session['user_level'] = $userlist1['level'];
                    if($userInfo){
                        $userInfo->session_id = $session['session_id'];
                        $userInfo->save();
                    }else{
                        $usersecond->session_id = $session['session_id'];
                        $usersecond->save();
                    }
                    return $this->getjson(1,$userlist1);
                }else{
                    return $this->getjson(0,'此手机号不存在,请注册后登录');
                }

            }else{
                //接收参数失败
                return $this->getjson(0,'后台接收参数失败,请重试');
            }
        }else{
            return $this->getjson(0,'后台接收参数失败,请重试');
        }
    }

//     public function actionDologin()
//     {
//         $model = new User();
//         $secondmodel = new UserSecondary;
//         if(Yii::$app->request->isPost){
//             $data = Yii::$app->request->post();
//             if($data){
//                 //查询是否存在     并且需要判断状态
//                 $userInfo1 = $model::find()->where(["phone"=>$data['phone']])->one();
//                 $usersecond1 = $secondmodel::find()->where(["phone"=>$data['phone']])->one();
//                 $userInfo = $model::find()->where(["phone"=>$data['phone'],'status'=>1])->one();
//                 $usersecond = $secondmodel::find()->where(["phone"=>$data['phone'],'status'=>1])->one();

//                 if($userInfo1 && !$userInfo){
//                     return $this->getjson(0,'此账号已经被冻结,请联系管理员');
//                 }

//                 if($usersecond1 && !$usersecond){
//                     return $this->getjson(0,'此账号已经被冻结,请联系管理员');
//                 }

//                 if(!$userInfo && !$usersecond){
//                     return $this->getjson(0,'此手机号不存在,请注册后登录');
//                 }
//                 //判断使用权是否过期
//                 if($userInfo){
//                     $user_id = $userInfo['id'];
//                 }
//                 if($usersecond){
//                     $user_id = $usersecond['user_id'];
//                 }


//                 $usersign = new UserSignin();
//                 $expried_time = $usersign::find()->where(['user_id'=>$user_id,'status'=>1])->one();
//                 if(!(strtotime($expried_time['expired_time'])-strtotime('now'))){
//                     return $this->getjson(0,'您的使用权已经过期,请购买');
//                 }

//                 //判断密码是否正确,如果存在,则更新用户最后登录的ip和最后登录的时间
//                 if($userInfo || $usersecond){
//                     if($userInfo['password'] == $data['password'] && $userInfo['phone'] == $data['phone']){
//                         //(1).同一个浏览器中不能重复登陆,先判断Session_id是否存在
//                         $session_id = Yii::$app->session->id;
//                         if($session_id == $userInfo->session_id){
//                             return $this->getjson(0,'该用户已经登陆,请勿重复登陆1');
//                         }
//                         //(2)判断用户是否正点击退出键退出
//                         if(!$userInfo->is_login){
//                             $userlist = $userInfo;
//                             $level = 1;
//                             $userInfo->last_login_time = date('Y-m-d H:i:s',strtotime('now'));
//                             $userInfo->last_login_ip = $data['ip'];
//                             $userInfo->is_login = 1;
//                             $userInfo->save();
//                         }else{
//                             //(3)假如没有点击退出键  判断Session_id存在      如果不存在,则证明已经下线,而且是非正常的下线,更改数据库状态,
//                             if(empty($session_id)){
//                                 $userlist = $userInfo;
//                                 $level = 1;
//                                 $userInfo->last_login_time = date('Y-m-d H:i:s',strtotime('now'));
//                                 $userInfo->last_login_ip = $data['ip'];
//                                 $userInfo->is_login = 1;
//                                 $userInfo->save();
//                             }else{
//                                 return $this->getjson(0,'该用户已经登陆,请勿重复登陆2');
//                             }
//                         }

//                     }elseif($usersecond['password'] == $data['password'] && $usersecond['phone'] == $data['phone']){
//                         //(1).同一个浏览器中不能重复登陆,先判断Session_id是否存在
//                         $session_id = Yii::$app->session->id;
// //                        echo $session_id;
// //                        echo '<br>';
// //                        echo $usersecond->session_id;
// //                        echo '<br>';
// //                        die();
//                         if($session_id == $usersecond->session_id){
//                             return $this->getjson(0,'该用户已经登陆,请勿重复登陆1');
//                         }
//                         //(2)判断用户是否正点击退出键退出
//                         if(!$usersecond->is_login){
//                             $userlist = $usersecond;
//                             $level = 2;
//                             $usersecond->last_login_time = date('Y-m-d H:i:s',strtotime('now'));
//                             $usersecond->last_login_ip = $data['ip'];
//                             $usersecond->is_login = 1;
//                             $usersecond->save();
//                         }else{
//                             echo $session_id;
//                             //(3)假如没有点击退出键  判断Session_id存在      如果不存在,则证明已经下线,而且是非正常的下线,更改数据库状态,
//                             if(empty($session_id)){
//                                 $userlist = $usersecond;
//                                 $level = 2;
//                                 $usersecond->last_login_time = date('Y-m-d H:i:s',strtotime('now'));
//                                 $usersecond->last_login_ip = $data['ip'];
//                                 $usersecond->is_login = 1;
//                                 $usersecond->save();
//                             }else{
//                                 return $this->getjson(0,'该用户已经登陆,请勿重复登陆2');
//                             }
//                         }
//                     }else{
//                         return $this->getjson(0,'手机号不存在,或者密码错误');
//                     }

//                     $userlist1['userid'] = $userlist['id'];
//                     $userlist1['name'] = $userlist['name'];
//                     $userlist1['password'] = $userlist['password'];
//                     $userlist1['site'] = $userlist['site'];
//                     $userlist1['level'] = $level;
//                     //存入Session
//                     $session = \Yii::$app->session;
//                     $session->set('userInfo',['level'=>$level,'id'=>$userlist['id']]);
//                     $session_id = Yii::$app->session->id;
//                     //将Session_id存入数据库
//                     if($userInfo){
//                         $userInfo->session_id = $session_id;
//                         $userInfo->save();
//                     }else{
//                         $usersecond->session_id = $session_id;
//                         $usersecond->save();
//                     }
//                     return $this->getjson(1,$userlist1);
//                 }else{
//                     return $this->getjson(0,'此手机号不存在,请注册后登录');
//                 }

//             }else{
//                 //接收参数失败
//                 return $this->getjson(0,'后台接收参数失败,请重试');
//             }
//         }else{
//             return $this->getjson(0,'后台接收参数失败,请重试');
//         }
//     }
//我们这使用你们相同的环境测试 本地和线上都正常, 我们不知道你那边更改了哪些东西, 没办法进行测试

    /**
     * register
     *
     * @return json
     */
    public function actionRegister()
    {
        $model = new User();
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            //判断改手机号是否存在
            $secondmodel = new UserSecondary;
            $userInfo = $secondmodel::find()->where(['phone'=>$data['phone']])->one();
            $user = User::find()->where(['phone'=>$data['phone']])->one();
            if($userInfo){
                return $this->getjson(0,'该手机已被注册为2级用户,不能重新注册');
            }
            if($user){
                return $this->getjson(0,'该手机已被注册为1级用户,不能重新注册');
            }
            //判断验证码是否正确
            $model1 = new UserCode();
            $codelist = $model1::find()->where(['phone'=>$data['phone']])->orderBy('id desc')->one();
            if($data['code'] == $codelist['code']){
                //存入数据库
                $model->phone    = $data['phone'];
                $model->name     = $data['name'];
                $model->password = $data['password'];
                $model->create_time = date('Y-m-d H:i:s',strtotime('now'));

                if($model->save()){
                    //添加到用户试用的表
                    $model2 = new UserSignin();
                    $model2->user_id = $model->id;
                    $model2->signin_time = date('Y-m-d H:i:s',strtotime('now'));
                    $model2->expired_time = date('Y-m-d H:i:s',strtotime('+7days'));
                    if(!$model2->save()){
                        return $this->getjson(0,'注册失败,请重试');
                    }
                    return $this->getjson(1,'注册成功,请登录');
                }else{
                    return $this->getjson(0,'注册失败,请重试');
                }
            }else{
                return $this->getjson(0,'验证码错误或者已经过期');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * forgetpassword
     *
     * @return json
     */
    public function actionForgetpassword()
    {
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($data){
                //判断电话是否在数据库中,判断code是否正确
                $model = new User();
                $userInfo = $model::find()->where(['phone'=>$data['phone']])->one();
                if($userInfo){
                    //判断验证码是否正确
                    $model1 = new UserCode();
                    $codelist = $model1::find()->where(['phone'=>$data['phone']])->orderBy('id desc')->one();
                    if($data['code'] == $codelist['code']){
                        //更新密码
                        $userInfo->password = $data['password'];
                        if($userInfo->save()){
                            return $this->getjson(1,'更新成功,请登录');
                        }else{
                            return $this->getjson(0,'更新密码失败,请重试');
                        }
                    }else{
                        return $this->getjson(0,'验证码错误或者已经过期');
                    }
                }else{
                    return $this->getjson(0,'该手机号尚未注册,请重试');
                }
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * logout
     *
     * @return json
     */
    public function actionLogout()
    {

        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($data){
                //判断级别
                if($data['level'] == 1){
                    //修改一级用户的登录状态为0
                    $user = User::find()->where('id = :id',[':id' => $data['id']])->one();
                    if($user){
                        Yii::$app->session->destroy();
                        $user->is_login = 0;
                        $user->session_id = null;
                        if($user->save()){
                            return $this->getjson(1,'退出成功');
                        }
                    }
                }else{
                    //修改二级用户的登录状态为0
                    $secondUser = UserSecondary::find()->where('id = :id',[':id' => $data['id']])->one();
                    if($secondUser){
                        Yii::$app->session->destroy();
                        $secondUser->is_login = 0;
                        $secondUser->session_id = null;
                        if($secondUser->save()){
                            return $this->getjson(1,'退出成功');
                        }
                    }
                }
                return $this->getjson(0,'退出失败');
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }

    /**
     * user center
     *
     * @return json
     */
    public function actionUserslist()
    {
        if(Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            if($data){
                //判断改手机号的用户是一级用户,还是二级用户
                $user = new User();
                $seconduser = new UserSecondary;
                $userInfo = $user::find()->where(['id'=>$data['userid'],'status'=>1])->one();
                $secondInfo = $seconduser::find()->where(['id'=>$data['userid'],'status'=>1])->one();
                $arr = [];
                if(!$userInfo && !$secondInfo){
                    return $this->getjson(0,'该用户不存在');
                }

                if($userInfo){
                    //获得用户列表信息
                    $secondlist = $seconduser::find()->where(['user_id'=>$userInfo['id'],'status'=>1])->all();
                }
                if($secondInfo){
                    //先查询父类的id
                    $userInfo = $user::find()->where(['id'=>$secondInfo['user_id']])->one();
                    $secondlist = $seconduser::find()->where(['user_id'=>$userInfo['id'],'status'=>1])->all();
                }
                //返回信息
                $arr[] = [
                    'id'=>$userInfo['id'],
                    'userid'=>0,
                    'name'=>$userInfo['name'],
                    'password'=>$userInfo['password'],
                    'phone'=>$userInfo['phone'],
                    'site'=>$userInfo['site'],
                    'role'=>1,
                ];
                if($secondlist){
                    $count = count($secondlist);
                    for($i = 0;$i < $count;$i++){
                        $arr[] = [
                            'id'=>$secondlist[$i]['id'],
                            'userid'=>$secondlist[$i]['user_id'],
                            'name'=>$secondlist[$i]['name'],
                            'password'=>$secondlist[$i]['password'],
                            'phone'=>$secondlist[$i]['phone'],
                            'site'=>$secondlist[$i]['site'],
                            'role'=>0,
                        ];
                    }
                }
                return $this->getjson(1,$arr);
            }else{
                return $this->getjson(0,'参数不能为空');
            }
        }else{
            return $this->getjson(0,'接收参数失败,请重试');
        }
    }
    /**
     * register
     *
     * @return json
     */
    public function actionSendsms()
    {
        if(!Yii::$app->request->isPost) {
            return $this->getjson(0,'不是post传参');
        }
        $data = Yii::$app->request->post();
        if(!$data){
            return $this->getjson(0,'没有传递参数');
        }
        $phone = $data['phone'];
        //判断该手机账号是否存在
        $model1 = new User();
        $userInfo = $model1::find()->where(['phone'=>$phone])->one();
        $secondInfo = UserSecondary::find()->where(['phone'=>$data['phone']])->one();
        if($data['forget']){
            if(!$userInfo && !$secondInfo){
                return $this->getjson(0,'该手机号尚未注册');
            }
        }else{
            if($userInfo || $secondInfo){
                return $this->getjson(0,'该手机号已经存在,请登录');
            }
        }
        $code = $this->getchars();
        $params = array ();
        $accessKeyId = "LTAIS0CyDNKAPLN3";
        $accessKeySecret = "Y1oHNHvaOzwiiXYSTpjtn9cJLUEG8M";
        $params["PhoneNumbers"] = $phone;
        $params["SignName"] = "同济医疗";
        $params["TemplateCode"] = "SMS_130220123";
        $params['TemplateParam'] = Array (
            "code" => $code,
        );
        // $params['OutId'] = "12345";
        // $params['SmsUpExtendCode'] = "1234567";
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        // $helper = new SignatureHelper();
        // 此处可能会抛出异常，注意catch
        $content = $this->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        );
        if($content->Message == 'OK'){
            //存入数据库
            $model = new UserCode();
            $model->phone = $phone;
            $model->code = $code;
            $model->create_time = date('Y-m-d H:i:s',strtotime('now'));
            if($model->save()){
                return $this->getjson(1,'发送成功');
            }
        }
        return $this->getjson(0,'发送失败请重试');
    }

    public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false) {
        $apiParams = array_merge(array (
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));

        $signature = $this->encode($sign);

        $url = ($security ? 'https' : 'http')."://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = $this->fetchContent($url);
            return json_decode($content);
        } catch( \Exception $e) {
            return false;
        }
    }

    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

    private function fetchContent($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));

        if(substr($url, 0,5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }

    private function getchars($length = 6)
    {
        $chars = '1234567890';
        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }
}




















